package top.jiangqiang.crawler.core.recorder.impl;

import org.dromara.hutool.core.collection.CollUtil;
import org.jetbrains.annotations.Nullable;
import top.jiangqiang.crawler.core.entities.Crawler;
import top.jiangqiang.crawler.core.recorder.RecorderService;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

public class DefaultRecorderService implements RecorderService {
    private final LinkedBlockingQueue<Crawler> queue = new LinkedBlockingQueue<>();
    private final ConcurrentHashMap<String, Crawler> map = new ConcurrentHashMap<>();

    @Nullable
    @Override
    public Crawler poll(long timeout) {
        try {
            return queue.poll(timeout, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            return null;
        }
    }

    @Override
    public void push(List<Crawler> crawlers) {
        if (CollUtil.isNotEmpty(crawlers)) {
            for (Crawler crawler : crawlers) {
                String id = crawler.getIdSupplier().get();
                synchronized (this) {
                    if (map.get(id) == null) {
                        map.put(id, crawler);
                        queue.offer(crawler);
                        System.out.println();
                    }
                }
            }
        }
    }



}
